package com.feng.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.feng.constants.SystemConstants;
import com.feng.domain.entity.LoginUser;
import com.feng.domain.entity.User;
import com.feng.mapper.MenuMapper;
import com.feng.mapper.UserMapper;
import com.feng.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(User::getUserName, username);
        User user = userMapper.selectOne(queryWrapper);
        if(Objects.isNull(user)){
            throw new RuntimeException("用户名或密码错误!");
        }

        // TODO 用户权限验证
        if(user.getType().equals(SystemConstants.ADMAIN)){
            List<String> permissions = menuMapper.selectMenuByUserId(user.getId());
            return new LoginUser(user, permissions);
        }

        return new LoginUser(user, null);
    }
}
